package com.by.course.config.web.jwt;

import cn.hutool.core.util.RandomUtil;
import com.by.course.entity.constant.Constant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author zhd
 * @date 2023/09/12 19:21
 **/
@Slf4j
@Service
public class JwtServiceImpl implements JwtService {

    /**
     * 过期时间: 24小时  1年
     */
    public static final long EXPIRATION_TIME = 12 * 30L * 24 * 60 * 60 * 1000L;

    @Override
    public String getJwt(Long userId, String openId) {
        return Jwts.builder()
                .claim("userId", userId)
                .claim("openId", openId)
                .claim("UUID", RandomUtil.randomLong())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .setSubject(openId)
                .signWith(SignatureAlgorithm.HS256, Constant.JWT_KEY)
                .setIssuedAt(new Date())
                .compact();
    }

    @Override
    public Claims verifyJwt(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(Constant.JWT_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
           log.info("verifyJwt 解析失败, token:{}", token);
        }
        return claims;
    }

    @Override
    public boolean isTokenExpired(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(Constant.JWT_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            return claims.getExpiration().before(new Date());
        } catch (Exception e) {
            log.info("isTokenExpired 解析失败, token:{},error: ", token, e);
            return true;
        }
    }
}
